<template>
  <view class="bg-gray-50 min-h-screen">
    <!-- 顶部导航 -->
    <PageHeader title="签到人员列表" :showBack="true" />

    <!-- 搜索和筛选区域 -->
    <view class="p-[32rpx] mb-[20rpx]">
      <!-- 搜索框 -->

      <!-- 日期选择 -->
      <!-- <view class="mb-[24rpx]">
        <view class="text-[28rpx] font-medium text-gray-800 mb-[16rpx]">日期筛选</view>
        <view class="flex gap-[20rpx]">
          <view class="flex-1">
            <view class="text-[24rpx] text-gray-600 mb-[8rpx]">开始日期</view>
            <view
              class="bg-gray-50 rounded-[16rpx] px-[24rpx] py-[20rpx] text-[28rpx] cursor-pointer border border-gray-300"
              @click="showStartDatePicker = true"
            >
              {{ startDate || '请选择开始日期' }}
            </view>
          </view>
          <view class="flex-1">
            <view class="text-[24rpx] text-gray-600 mb-[8rpx]">结束日期</view>
            <view
              class="bg-gray-50 rounded-[16rpx] px-[24rpx] py-[20rpx] text-[28rpx] cursor-pointer border border-gray-300"
              @click="showEndDatePicker = true"
            >
              {{ endDate || '请选择结束日期' }}
            </view>
          </view>
        </view>
        <view class="flex flex-wrap gap-[12rpx] mt-[16rpx]">
          <view
            v-for="(quickDate, index) in quickDates"
            :key="index"
            class="px-[20rpx] py-[8rpx] rounded-[12rpx] text-[24rpx] cursor-pointer transition-all duration-200"
            :class="
              quickDate.active
                ? 'bg-blue-600 text-white'
                : 'bg-gray-50 text-gray-600'
            "
            @click="handleQuickDateSelect(quickDate)"
          >
            {{ quickDate.label }}
          </view>
        </view>
      </view> -->

      <!-- 查询按钮 -->
      <!-- <view class="mt-[24rpx] flex gap-[16rpx]">
        <nut-button
          type="primary"
          class="flex-1 bg-blue-600 border-none"
          @click="handleQuery"
          :loading="loading"
        >
          {{ loading ? '查询中...' : '查询' }}
        </nut-button>
        <nut-button
          type="info"
          class="flex-1 bg-blue-100 text-blue-600 border-none"
          @click="handleReset"
        >
          重置
        </nut-button>
      </view> -->
    </view>

    <!-- 日期选择器 -->
    <nut-popup v-model:visible="showStartDatePicker" position="bottom" round>
      <nut-date-picker
        v-model="startDateValue"
        title="选择开始日期"
        type="date"
        @confirm="onStartDateConfirm"
        @cancel="showStartDatePicker = false"
      />
    </nut-popup>

    <nut-popup v-model:visible="showEndDatePicker" position="bottom" round>
      <nut-date-picker
        v-model="endDateValue"
        title="选择结束日期"
        type="date"
        @confirm="onEndDateConfirm"
        @cancel="showEndDatePicker = false"
      />
    </nut-popup>

    <!-- 人员列表 -->
    <view class="px-[32rpx] pb-[32rpx]">
      <view
        v-for="(person, index) in filteredList"
        :key="person.id"
        class="bg-white rounded-[20rpx] p-[32rpx] mb-[20rpx] shadow-sm hover:shadow-md transition-all duration-300"
      >
        <!-- 人员信息 -->
        <view class="flex items-center justify-between">
          <view class="flex items-center">
            <view class="w-[80rpx] h-[80rpx] rounded-full bg-blue-100 flex items-center justify-center mr-[20rpx] overflow-hidden">
              <img
                v-if="person.avatar"
                :src="person.avatar"
                class="w-full h-full object-cover"
                alt="头像"
              />
              <text v-else class="text-[32rpx] font-bold text-blue-600">
                {{ person.name?.charAt(0) || '用' }}
              </text>
            </view>
            <view>
              <view class="text-[30rpx] font-bold text-gray-800 mb-[8rpx]">
                {{ person.name }}
              </view>
              <view class="text-[24rpx] text-gray-600">
                ID: {{ person.id }}
              </view>
            </view>
          </view>
          
          <!-- 签到状态 -->
          <view
            class="px-[16rpx] py-[8rpx] rounded-[12rpx] text-[22rpx] font-medium"
            :class="
              person.signed
                ? 'bg-green-100 text-green-700'
                : 'bg-orange-100 text-orange-600'
            "
          >
            {{ person.signed ? '签到成功' : '签到失败' }}
          </view>
        </view>

        <!-- 签到时间 -->
        <view class="mt-[16rpx] p-[16rpx] bg-gray-50 rounded-[12rpx]">
          <view class="flex items-center">
            <IconFont name="clock" class="text-[24rpx] text-gray-600 mr-[8rpx]" />
            <text class="text-[24rpx] text-gray-600">签到时间：{{ person.signTime }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <!-- <view class="flex justify-end gap-[16rpx] mt-[16rpx] pt-[16rpx] border-t border-gray-200">
          <nut-button
            size="small"
            type="info"
            class="bg-blue-100 text-blue-600 border-none"
            @click="handleViewDetail(person)"
          >
            查看详情
          </nut-button>
          <nut-button
            v-if="!person.signed"
            size="small"
            type="primary"
            class="bg-green-500 border-none"
            @click="handleManualSign(person)"
          >
            手动签到
          </nut-button>
          <nut-button
            v-if="person.signed"
            size="small"
            type="danger"
            class="bg-red-500 border-none"
            @click="handleCancelSign(person)"
          >
            取消签到
          </nut-button>
        </view> -->
      </view>

      <!-- 空状态 -->
      <view v-if="filteredList.length === 0" class="text-center py-[100rpx]">
        <IconFont name="empty" class="text-[120rpx] text-gray-400 mb-[20rpx]" />
        <view class="text-[28rpx] text-gray-500">暂无签到记录</view>
        <view class="text-[24rpx] text-gray-400 mt-[8rpx]">请选择其他日期范围查询</view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore" class="text-center py-[32rpx]">
      <nut-button
        type="info"
        class="bg-blue-100 text-blue-600 border-none"
        @click="loadMore"
        :loading="loading"
      >
        {{ loading ? '加载中...' : '加载更多' }}
      </nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue-taro'
import PageHeader from '@/components/PageHeader.vue'
import { post } from '@/utils/request'

// 定义接口
interface SignPerson {
  id: number
  name: string
  avatar?: string
  signed: boolean
  signTime?: string
}

// 路由参数
const taskId = ref<number>(0);
const pageParams = Taro.getCurrentInstance().router?.params || {};

// memberId=${item.member_id}&id

// 搜索和筛选
const searchText = ref('')
const activeFilter = ref('all')
const filters = ref([
  { label: '全部', value: 'all' },
  { label: '已签到', value: 'signed' },
  { label: '未签到', value: 'unsigned' }
])

// 日期选择相关
const startDate = ref(new Date().toISOString().split('T')[0])
const endDate = ref(new Date().toISOString().split('T')[0])
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)
const startDateValue = ref(new Date().toISOString().split('T')[0])
const endDateValue = ref(new Date().toISOString().split('T')[0])

// 快速日期选择
const quickDates = ref([
  { label: '今天', value: 'today', active: false },
  { label: '昨天', value: 'yesterday', active: false },
  { label: '最近7天', value: 'last7days', active: false },
  { label: '最近30天', value: 'last30days', active: false },
  { label: '本月', value: 'thisMonth', active: false },
  { label: '上月', value: 'lastMonth', active: false }
])

// 数据
const signList = ref<SignPerson[]>([])
const loading = ref(false)
const hasMore = ref(true)
const pageNo = ref(1)
const pageSize = ref(20)

// 筛选后的列表（暂时直接返回原列表，因为搜索和状态筛选已隐藏）
const filteredList = computed(() => {
  return signList.value
})

// 获取签到人员列表
const getSignList = async (isLoadMore = false) => {
  try {
    loading.value = true
    pageParams.memberId
    const params = {
      id: pageParams.id,
      pageNo: pageNo.value,
      pageSize: 100,
      memberId:pageParams.memberId
    }

    const res = await post('/check/checkinRecord', params)
    
    if (res.code === 0) {
             const newList = res.data.map((obj: any) => {
         const item = obj.columns
         return {
           id: item.id,
           name: item.name || '未知用户',
           avatar: item.avatar_url,
           signTime: item.sign_time,
           signed: item.status == 1,
         }
       })

      if (isLoadMore) {
        signList.value.push(...newList)
      } else {
        signList.value = newList
      }

      hasMore.value = newList.length === pageSize.value
    } else {
      Taro.showToast({
        title: res.message || '获取数据失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取签到列表失败:', error)
    Taro.showToast({
      title: '获取数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  // 搜索时保持当前日期筛选条件
  // 不需要重置页码，因为搜索是实时进行的
}

// 筛选处理
const handleFilterChange = (value: string) => {
  activeFilter.value = value
}

// 快速日期选择处理
const handleQuickDateSelect = (quickDate: any) => {
  // 重置所有快速日期选择状态
  quickDates.value.forEach(item => item.active = false)
  quickDate.active = true

  const today = new Date()
  const year = today.getFullYear()
  const month = today.getMonth()
  const date = today.getDate()

  switch (quickDate.value) {
    case 'today':
      startDate.value = formatDate(today)
      endDate.value = formatDate(today)
      break
    case 'yesterday':
      const yesterday = new Date(today)
      yesterday.setDate(date - 1)
      startDate.value = formatDate(yesterday)
      endDate.value = formatDate(yesterday)
      break
    case 'last7days':
      const last7days = new Date(today)
      last7days.setDate(date - 7)
      startDate.value = formatDate(last7days)
      endDate.value = formatDate(today)
      break
    case 'last30days':
      const last30days = new Date(today)
      last30days.setDate(date - 30)
      startDate.value = formatDate(last30days)
      endDate.value = formatDate(today)
      break
    case 'thisMonth':
      startDate.value = `${year}-${String(month + 1).padStart(2, '0')}-01`
      endDate.value = formatDate(today)
      break
    case 'lastMonth':
      const lastMonth = new Date(year, month - 1, 1)
      const lastMonthEnd = new Date(year, month, 0)
      startDate.value = formatDate(lastMonth)
      endDate.value = formatDate(lastMonthEnd)
      break
  }
}

// 开始日期确认
const onStartDateConfirm = (val: any) => {
  showStartDatePicker.value = false
  startDate.value = formatDate(val)
  // 重置快速日期选择状态
  quickDates.value.forEach(item => item.active = false)
}

// 结束日期确认
const onEndDateConfirm = (val: any) => {
  showEndDatePicker.value = false
  endDate.value = formatDate(val)
  // 重置快速日期选择状态
  quickDates.value.forEach(item => item.active = false)
}

// 格式化日期
const formatDate = (date: Date | any) => {
  if (typeof date === 'string') {
    return date
  }
  if (date && typeof date === 'object' && Array.isArray(date.selectedValue)) {
    return date.selectedValue.join('-')
  }
  if (date instanceof Date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  return ''
}

// 查询处理
const handleQuery = () => {
  pageNo.value = 1
  getSignList()
}

// 重置处理
const handleReset = () => {
  startDate.value = ''
  endDate.value = ''
  // 重置快速日期选择状态
  quickDates.value.forEach(item => item.active = false)
  // 重新查询
  pageNo.value = 1
  getSignList()
}

// 加载更多
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    pageNo.value++
    getSignList(true)
  }
}

// 查看详情
const handleViewDetail = (person: SignPerson) => {
  Taro.navigateTo({
    url: `/pages/post/sign-detail?id=${person.id}&taskId=${taskId.value}`
  })
}

// 手动签到
const handleManualSign = (person: SignPerson) => {
  Taro.showModal({
    title: '确认签到',
    content: `确定要为 ${person.name} 手动签到吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const signRes = await post('/task/manual-sign', {
            taskId: taskId.value,
            personId: person.id
          })
          
          if (signRes.code === 0) {
            Taro.showToast({
              title: '签到成功',
              icon: 'success'
            })
            // 刷新列表
            getSignList()
          } else {
            Taro.showToast({
              title: signRes.message || '签到失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('手动签到失败:', error)
          Taro.showToast({
            title: '签到失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 取消签到
const handleCancelSign = (person: SignPerson) => {
  Taro.showModal({
    title: '确认取消',
    content: `确定要取消 ${person.name} 的签到记录吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const cancelRes = await post('/task/cancel-sign', {
            taskId: taskId.value,
            personId: person.id
          })
          
          if (cancelRes.code === 0) {
            Taro.showToast({
              title: '取消成功',
              icon: 'success'
            })
            // 刷新列表
            getSignList()
          } else {
            Taro.showToast({
              title: cancelRes.message || '取消失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('取消签到失败:', error)
          Taro.showToast({
            title: '取消失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 页面加载
onMounted(() => {
  const params = Taro.getCurrentInstance().router?.params
  if (params?.id) {
    taskId.value = Number(params.id)
    getSignList()
  } else {
    Taro.showToast({
      title: '缺少任务ID参数',
      icon: 'none'
    })
    setTimeout(() => {
      Taro.navigateBack()
    }, 1500)
  }
})
</script>

<style lang="scss" scoped>
.nut-button {
  border-radius: 12rpx !important;
  font-weight: 500 !important;
}

// 添加悬停效果
.bg-white {
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
  }
}

// 搜索框样式
.nut-input {
  border: none !important;
  background: #f5f7fa !important;
  
  &__input {
    background: transparent !important;
  }
}
</style>
